import React from 'react';
import { Modal, DatePickerView, PickerView, Toast } from 'antd-mobile';
import cn from 'classnames';
import moment from 'moment';
import { isDate } from 'lodash';
import styles from './index.less';

function dateToStr(date, format = 'YYYY-MM-DD') {
    if (date) {
        return moment(date).format(format);
    }
    return null;
}

const endTypeList = [
    {
        label: '至今',
        value: 0
    },
    {
        label: '其他',
        value: 1
    }
];

const RangePicker = React.forwardRef(({ value = [], mode = 'date', showNow = false, children, onChange }, ref) => {
    const [visible, setVisible] = React.useState(false);
    const [active, setActive] = React.useState(0);
    const [dates, setDates] = React.useState([]);
    const [endType, setEndType] = React.useState(0);

    React.useEffect(() => {
        if (visible) {
            setDates(value.map(item => (item ? new Date(item) : undefined)));
            if (value?.[1]) {
                setEndType(1);
            } else {
                setEndType(0);
            }
        }
    }, [JSON.stringify(value), visible]);

    React.useEffect(() => {
        if (!visible) {
            setActive(0);
        }
    }, [visible]);

    const handleOpen = e => {
        e.preventDefault();
        setVisible(true);
    };

    const handleClose = () => {
        setVisible(false);
    };

    const handleChange = (date, type) => {
        if (type === 'start') {
            const arr = [...dates];
            arr.splice(0, 1, date);
            // if (dates?.[1] && moment(date).isAfter(dates[1])) {
            //     arr.splice(1, 1, date);
            // }
            setDates(arr);
            return;
        }
        if (type === 'end') {
            const arr = [...dates];
            setDates([arr.shift()].concat(date));
        }
    };

    const handleTypeChange = v => {
        setEndType(v[0]);
        const arr = [...dates];
        if (v[0] === 0) {
            setDates([arr.shift()]);
        } else {
            setDates([arr.shift()].concat(new Date()));
        }
    };

    const handleSubmit = () => {
        if (dates?.[1] && moment(dates[0]).isAfter(dates[1])) {
            Toast.info('结束时间不可小于开始时间');
            return;
        }
        if (!dates[0]) {
            dates[0] = new Date();
        }
        if (!showNow && !dates[1]) {
            dates[1] = new Date();
        }
        if (onChange) onChange(dates.map(item => dateToStr(item)));
        setVisible(false);
    };

    const getInitialValue = d => {
        if (d && isDate(d)) {
            return d;
        }
        return new Date();
    };

    return (
        <div ref={ref}>
            <div onClick={handleOpen}>
                {React.Children.map(children, child =>
                    React.cloneElement(child, {
                        value
                    })
                )}
            </div>
            <Modal popup className={styles.modalWrap} visible={visible} onClose={handleClose} animationType="slide-up">
                <div className={styles.rangeWrap}>
                    <div className={styles.rangeHead}>
                        <a className={cn(styles.cancelBtn, styles.btn)} onClick={() => setVisible(false)}>
                            取消
                        </a>
                        <div className={styles.selectBtn}>
                            <div className={cn({ [styles.active]: active === 0 })} onClick={() => setActive(0)}>
                                开始时间
                            </div>
                            <div className={cn({ [styles.active]: active === 1 })} onClick={() => setActive(1)}>
                                结束时间
                            </div>
                        </div>
                        <a className={styles.btn} onClick={handleSubmit}>
                            确定
                        </a>
                    </div>
                    {active === 0 ? (
                        <DatePickerView
                            mode={mode}
                            minDate={new Date(1970, 0, 1)}
                            maxDate={new Date()}
                            value={getInitialValue(dates?.[0])}
                            onChange={e => handleChange(e, 'start')}
                        />
                    ) : (
                        <>
                            {showNow ? (
                                <div style={{ display: 'flex' }}>
                                    <div style={{ width: '25%' }}>
                                        <PickerView
                                            cols={1}
                                            data={endTypeList}
                                            value={[endType]}
                                            onChange={handleTypeChange}
                                        />
                                    </div>
                                    <div style={{ flex: 1 }}>
                                        {endType === 1 ? (
                                            <DatePickerView
                                                mode={mode}
                                                minDate={new Date(1970, 0, 1)}
                                                maxDate={new Date()}
                                                value={getInitialValue(dates?.[1])}
                                                onChange={e => handleChange(e, 'end')}
                                            />
                                        ) : (
                                            <PickerView cols={3} />
                                        )}
                                    </div>
                                </div>
                            ) : (
                                <DatePickerView
                                    mode={mode}
                                    minDate={new Date(1970, 0, 1)}
                                    maxDate={new Date()}
                                    value={getInitialValue(dates?.[1])}
                                    onChange={e => handleChange(e, 'end')}
                                />
                            )}
                        </>
                    )}
                </div>
            </Modal>
        </div>
    );
});

export default RangePicker;
